	package gui.engraving;


	import javax.swing.JPanel;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;

import entities.Employee;
import entities.ProductionOrder;

import javax.swing.border.TitledBorder;

import java.awt.Color;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.miginfocom.swing.MigLayout;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.JButton;

import utilities.Services;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;

import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.SystemColor;
import java.awt.Font;
	
/**
 * @author Idan
 * This is the GUI class for the list of reports to be engraved
 */
public class EngravingListOfOrders extends JPanel
{
	private JTable table;
	private EngravingPanel myPanel;
	public DefaultTableModel model;
	private JButton createReport;
	public ArrayList<Object> listOfOrders;
	private JButton exitButton;
	private JButton button;


		public EngravingListOfOrders(EngravingPanel engravingPanel)
		{
			setBackground(new Color(176, 224, 230));
			this.myPanel=engravingPanel;
			setLayout(new FormLayout(new ColumnSpec[] {
					FormFactory.RELATED_GAP_COLSPEC,
					FormFactory.DEFAULT_COLSPEC,
					FormFactory.RELATED_GAP_COLSPEC,
					FormFactory.DEFAULT_COLSPEC,
					FormFactory.RELATED_GAP_COLSPEC,
					ColumnSpec.decode("center:default:grow"),
					FormFactory.RELATED_GAP_COLSPEC,
					FormFactory.DEFAULT_COLSPEC,
					FormFactory.RELATED_GAP_COLSPEC,
					FormFactory.DEFAULT_COLSPEC,
					FormFactory.RELATED_GAP_COLSPEC,},
				new RowSpec[] {
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,
					FormFactory.RELATED_GAP_ROWSPEC,
					RowSpec.decode("default:grow"),
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,
					FormFactory.RELATED_GAP_ROWSPEC,
					FormFactory.DEFAULT_ROWSPEC,
					FormFactory.RELATED_GAP_ROWSPEC,}));
			
			JPanel panel = new JPanel(){@Override
				public void paintComponent(Graphics g) {
		        Graphics2D g2d = (Graphics2D) g;
		        Color color1 = getBackground();
		        Color color2 = color1.darker();
		        int w = getWidth();
		        int h = getHeight(); 
		        GradientPaint gp = new GradientPaint(
		                0, 0, color1,
		                0, h, color2);

		        g2d.setPaint(gp);
		        g2d.fillRect(0, 0, w, h);
		        }};
			panel.setBackground(new Color(176, 224, 230));
			panel.setBorder(new TitledBorder(null, "\u05E8\u05E9\u05D9\u05DE\u05EA \u05E4\u05E7''\u05E2\u05D5\u05EA \u05DC\u05D7\u05E8\u05D9\u05D8\u05D4", TitledBorder.RIGHT, TitledBorder.TOP, null, new Color(59, 59, 59)));
			add(panel, "6, 4, center, fill");
			panel.setLayout(new MigLayout("", "[][600px:n,grow,center][]", "[300px:n,grow][29px]"));
			
			JScrollPane scrollPane = new JScrollPane();
			panel.add(scrollPane, "cell 1 0,grow");
			
			table = new JTable();
			table.setFont(new Font("Tahoma", Font.PLAIN, 15));
			table.addMouseListener(new MouseAdapter()
			{
				@Override
				public void mouseClicked(MouseEvent arg0)
				{
					if (arg0.getClickCount() == 2)
					{
						// Double click
						createReport(table.getSelectedRow());
					}
				}
			});
			table.setBorder(new TitledBorder(null, "", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
			table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			scrollPane.setViewportView(table);
			table.setModel(new DefaultTableModel(
				new Object[][] {
				},
				new String[] {
					"\u05DB\u05DE\u05D5\u05EA", "\u05EA\u05D0\u05E8\u05D9\u05DA", "\u05D3\u05D9\u05D5\u05E4\u05D8\u05E8", "\u05E1\u05D5\u05D2", "\u05E4\u05E7''\u05E2"
				}
			) {
				boolean[] columnEditables = new boolean[] {
					false, false, false, false, false
				};
				public boolean isCellEditable(int row, int column) {
					return columnEditables[column];
				}
			});
			table.getColumnModel().getColumn(0).setResizable(false);
			table.getColumnModel().getColumn(0).setPreferredWidth(50);
			table.getColumnModel().getColumn(0).setMinWidth(50);
			table.getColumnModel().getColumn(1).setResizable(false);
			table.getColumnModel().getColumn(1).setPreferredWidth(100);
			table.getColumnModel().getColumn(1).setMinWidth(100);
			table.getColumnModel().getColumn(2).setResizable(false);
			table.getColumnModel().getColumn(2).setPreferredWidth(50);
			table.getColumnModel().getColumn(2).setMinWidth(50);
			table.getColumnModel().getColumn(3).setResizable(false);
			table.getColumnModel().getColumn(3).setPreferredWidth(80);
			table.getColumnModel().getColumn(3).setMinWidth(80);
			table.getColumnModel().getColumn(4).setResizable(false);
			table.getColumnModel().getColumn(4).setPreferredWidth(110);
			table.getColumnModel().getColumn(4).setMinWidth(110);
			
			createReport = new JButton("יצירת דוח");
			createReport.setFont(new Font("Tahoma", Font.PLAIN, 13));
			createReport.setIcon(new ImageIcon(EngravingListOfOrders.class.getResource("/graphics/createReportPencil.png")));
			createReport.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent e)
				{

	            		int rowNumber = table.getSelectedRow();
	            		if (rowNumber==-1)
	            		{
	            			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
	            				    "יש לבחור ראשית פק''ע  מהרשימה.","שגיאה",JOptionPane.ERROR_MESSAGE);
	            		}
	            		else
	            		{
		            		createReport.setEnabled(false);
		            		createReport(rowNumber);
		            		createReport.setEnabled(true);
	            		}
	        		
				
				}
			});
			
			button = new JButton("רענן");
			button.setFont(new Font("Tahoma", Font.PLAIN, 13));
			button.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent arg0) 
				{
					refreshList();
				}
			});
			button.setIcon(new ImageIcon(EngravingListOfOrders.class.getResource("/graphics/refreshOrders.png")));
			panel.add(button, "flowx,cell 1 1");
		
			
			panel.add(createReport, "cell 1 1,alignx center,aligny center");
		
			this.model = (DefaultTableModel) table.getModel(); 
			
			exitButton = new JButton("יציאה");
			exitButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
			exitButton.setIcon(new ImageIcon(EngravingListOfOrders.class.getResource("/graphics/exit.png")));
			exitButton.addMouseListener(new MouseAdapter() 
			{
				@Override
				public void mouseClicked(MouseEvent e)
				{
					Object[] options = {"כן","לא"};
	        		int n = JOptionPane.showOptionDialog(myPanel, "האם ברצונך לצאת מהמערכת?","אישור יציאה", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,"");
	        		
	        		if (n==0)
	        		{
	        			if (myPanel.engravingClient != null)
	                    {
	                      try
	                      {
	                    	  myPanel.engravingClient.close();
	                      }
	                      catch (Exception ignore)
	                      {}
	                     }
	            		
	            		System.exit(0);
	        		}
				}
			});
			add(exitButton, "6, 6, center, center");
		} 



		


/**
 * refresh GUI
 */
		protected void refreshList() 
		{
			
			
			// clear table
			// clear the table
			for (int row=model.getRowCount()-1 ; row>=0;row--)
				model.removeRow(row);
		
			// repopulate table
			
			 ArrayList<Object> message = new ArrayList<Object>();
		        message.add("initializeAllFieldsEngraving");
		         
		        try 
		        {
		      //  	System.out.println("intialized for EngravingFrame");
		        	ArrayList<Object> response = myPanel.engravingClient.call(message);
		        	setVariables(response);
     
		        } catch (Exception ex)
		        {
		        	
		            Logger.getLogger(EngravingFrame.class.getName()).log(Level.SEVERE, null, ex);
		        }
		        
		
			
		
			
		}






/**
 * Initialize GUI data
 */
		public void setVariables(ArrayList<Object> response)
		{
			listOfOrders = new ArrayList<Object>();
			listOfOrders = (ArrayList<Object>) response.get(4);			
	    	// Old version
	    	 
	        for (int i=1; i<=((int)listOfOrders.get(0));i++)
	        {
	        	
	        	ProductionOrder order = (ProductionOrder)listOfOrders.get(i);
	        	model.addRow(new Object[]{order.getQuantity(),order.getDateAsString(),order.getDiopter(),order.getType(),order.getOrderID()});
	        	
	        
	        }
	
		}
		
	
		/**
		 * Initializes the create Report GUI
		 */
		private void createReport(int RowNumber)
		{
			myPanel.createReport.initializeByListOfOrdersTab((ProductionOrder)listOfOrders.get(RowNumber+1));
		}






/**
 * Removes an order from the table
 */
		public void removeFromTable(String orderID)
		{
			
			// get current number of orders in the table
			int ordersCounter = (int)(listOfOrders.get(0));
		
			// search the list for the orderID
			for ( int i=1; i<=ordersCounter ;i++ )
			{
				ProductionOrder temp = (ProductionOrder)listOfOrders.get(i);
		
				if (temp.getOrderID() == Integer.parseInt(orderID))
				{
				
					// remove order from the list
					listOfOrders.remove(i);
					// update the orders counter
					listOfOrders.set(0, ordersCounter-1);
					
					// clear the table
					for (int row=model.getRowCount()-1 ; row>=0;row--)
						model.removeRow(row);
						
					// create a fake response to be used by setVariables()
					ArrayList<Object> simulatedResponseArrayList = new ArrayList<Object>();
					simulatedResponseArrayList.add("0");
					simulatedResponseArrayList.add("1");
					simulatedResponseArrayList.add("2");
					simulatedResponseArrayList.add("3");
					simulatedResponseArrayList.add(listOfOrders);
					setVariables(simulatedResponseArrayList);
					break;
				}
				
			}
			
		}
		
	
		@Override
		public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        Color color1 = getBackground();
        Color color2 = color1.darker();
        int w = getWidth();
        int h = getHeight(); 
        GradientPaint gp = new GradientPaint(
                0, 0, color1,
                0, h, color2);

        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
        }
	
}
